<?php
/**
 * Created by PhpStorm.
 * User: sen
 * Date: 16/7/26
 * Time: 下午7:27
 */
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Banner;
use app\models\User;
use app\models\Upload;
use yii\web\UploadedFile;

//引入又拍云
include "vendor/upyun.class.php";

class BannerController extends Controller{


    public function init(){
        $this->enableCsrfValidation = false;
        if(!\Yii::$app->user->id){
            $url = \Yii::$app->request->getPathInfo();
            return $this->redirect('../login/index?url='.$url);
        }
        $userId = \Yii::$app->user->id;
        $user = new User();
        $admin = $user->findIdentity($userId);
        if($admin['type']==1 or $admin['type']==0){
            return $this->redirect('../login/logout');

        }
    }

    public function actionIndex(){
        $view = \Yii::$app->view;
        $view->params['menuitemid']=61;

        return $this->render("index");

    }


    //剪切图片,上传又拍云
    public function actionUpload(){

        $imgtype = array(
//            'gif'=>'gif',
            'png'=>'png',
            'jpg'=>'jpeg',
            'jpeg'=>'jpeg'
        ); //图片类型在传输过程中对应的头信息
        $message = $_POST['message']; //接收以base64编码的图片数据
        $filename = $_POST['filename']; //接收文件名称
        $ftype = $_POST['filetype'];  //接收文件类型
        //首先将头信息去掉，然后解码剩余的base64编码的数据
        $message = base64_decode(substr($message,strlen('data:image/'.$imgtype[strtolower($ftype)].';base64,')));
        $filename = $filename.".".$ftype;
        $furl = "../web/upload/";
        //开始写文件
        $filePath = $furl.date('U').rand(0,9999).$filename;
        $file = fopen($filePath,"w");
        if(fwrite($file,$message) === false){
            echo json_encode(array('code'=>1,'msg'=>'图片上传失败'));
            exit;
        }

        //裁剪图片
        $src_path = $filePath;
        //创建源图的实例
        $src = imagecreatefromstring(file_get_contents($src_path));
        //裁剪开区域左上角的点的坐标
        $x = $_POST['x'];
        $y = $_POST['y'];
        //裁剪区域的宽和高
        $width = $_POST['width'];
        $height = $_POST['height'];
        $bili=$_POST['bili'];
        //最终保存成图片的宽和高，和源要等比例，否则会变形
        $final_width = $width;
        $final_height = $height;
//            round($final_width * $height / $width);

        //将裁剪区域复制到新图片上，并根据源和目标的宽高进行缩放或者拉升
        $new_image = imagecreatetruecolor($final_width, $final_height);
        imagecopyresampled($new_image, $src, 0, 0, $x/$bili, $y/$bili, $final_width, $final_height, $width/$bili, $height/$bili);
        //输出图片
        if($ftype == $imgtype['jpg']){
            header('Content-Type: image/jpeg');
            imagejpeg($new_image,$src_path);
        }
        else{
            header('Content-Type: image/png');
            imagepng($new_image,$src_path);
        }
        imagedestroy($src);
        imagedestroy($new_image);
        fclose($file);
//        echo json_encode(array('code'=>0,'msg'=>'图片上传成功','imgSrc'=>'http://'.$src));
//        $testPath = dirname(__DIR__)."/web/images/close.png";
        //又拍云配置
        $config =  array(
            'user_name' => 'hacker',
            'pwd' => 'hacker1234',
            'bucket' => 'hackerdistribution',
            'picture_path' => $filePath,
        );
        //图片上传到又拍云
        $upyun = new \UpYun($config['bucket'], $config['user_name'], $config['pwd']);
        $filePath = str_replace('..',dirname(__DIR__),$filePath);
        $imgName = explode('upload/',$filePath)[1];
        $src='';  //图片src
        if (fopen($filePath,'r')){
            $fh = fopen($filePath,'r');
            // 获取图片体积大小
            $limit = $_POST['limit']; //限制图片大小
            $size = filesize($filePath);
            if($size>$limit){
                echo json_encode(array('code'=>2,'msg'=>'图片尺寸不符合','size'=>$size));
            }
            else{
                $upyun->writeFile('/banner/'.$imgName, $fh, True);   // 上传图片，自动创建目录
                $src = $config['bucket'].".b0.upaiyun.com"."/banner/".$imgName;
                echo json_encode(array('code'=>0,'msg'=>'图片上传成功','imgSrc'=>'http://'.$src));
            }
            fclose($fh);
            $create_time=date('Y-m-d H:i:s');
            $bannerModel=new Banner();
            $bannerModel->pic_url='http://'.$src;
            $bannerModel->create_time=$create_time;
            $bannerModel->save();

        }else
            echo json_encode(array('code'=>1,'msg'=>'图片上传失败'));

        //清除图片缓存
        //循环目录下的所有文件
        function delFileUnderDir( $dirName="../web/upload/" )
        {
            if ( $handle = opendir( "$dirName" ) ) {
                while ( false !== ( $item = readdir( $handle ) ) ) {
                    if ( $item != "." && $item != ".." ) {
                        if ( is_dir( "$dirName/$item" ) ) {
                            delFileUnderDir( "$dirName/$item" );
                        } else {
                            if( unlink( "$dirName/$item" ) );
                        }
                    }
                }
                closedir( $handle );
            }
        }
        delFileUnderDir('upload');

    }


    //轮播图的列表
    public function actionTableData(){

        //获取相应字段
        $request = \Yii::$app->request;
        $limit = $request->get('limit');
        $offset = $request->get('offset');
        $model = new Banner();
        $rs = $model->getTableData($limit,$offset);
        echo json_encode($rs);

    }

    //轮播图删除操作
    public function actionRemoveBanner(){

        //获取category_id字段
        $request = \Yii::$app->request;
        $banner_id = $request->get('banner_id');
        //删除标志位
        echo Banner::updateAll(['del_flag'=>'0'],['banner_id'=>$banner_id]);
    }


    //获取轮播图数量
    public function actionGetBannerNum(){
        $total = (new \yii\db\Query())
            ->from('hcps_banner')
            ->where(['del_flag' => 1])
            ->count();
        echo $total;
    }

    //保存修改
    public function actionSaveBanner(){
        //获取attr_id字段
        $request = \Yii::$app->request;
        $banner_id = $request->post('banner_id');//获取id
        $content = $request->post('content');
        $rs = \Yii::$app->db->createCommand()->update('hcps_banner', [
            'content' => $content,
        ], "banner_id=:banner_id", [
            ':banner_id' => $banner_id
        ])->execute();
        echo json_encode($rs);
    }


}